﻿using Yunwei.IDAL;
using System;
using System.Linq;
using System.Linq.Expressions;
using Yunwei.Domain.Models;
using System.Data.Entity.Validation;

namespace Yunwei.DAL
{
    /// <summary>
    /// 仓储基类
    /// <remarks>
    /// 创建：2014.02.03
    /// 修改：2014.02.16
    /// </remarks>
    /// </summary>
    public class BaseRepository<T>: IBaseRepository<T> where T : class 
    {
        //protected YunweiDbContext nContext = ContextFactory.GetCurrentContext();
        protected SmartRestaurantContext context = ContextFactory.GetCurrentContext();
        public IQueryable<T> Entities { get { return context.Set<T>(); } }

        public T Add(T entity, bool isSave = true)
        {
            try
            {
                context.Set<T>().Add(entity);
                if (isSave) context.SaveChanges();
            }
            catch (DbEntityValidationException ex)
            { 
            
            }
            catch (Exception ex)
            {

            }
            return entity;
        }

        public int Count(Expression<Func<T, bool>> predicate)
        {
            return context.Set<T>().Count(predicate);
        }

        public bool Update(T entity, bool isSave = true)
        {
            try
            {
                context.Set<T>().Attach(entity);
                context.Entry<T>(entity).State = System.Data.Entity.EntityState.Modified;
                return isSave ? context.SaveChanges() > 0 : true;
            }
            catch (DbEntityValidationException ex)
            {

            }
            catch (Exception ex)
            {

            }
            return false;
        }

        public bool Delete(T entity, bool isSave = true)
        {
            context.Set<T>().Attach(entity);
            context.Entry<T>(entity).State = System.Data.Entity.EntityState.Deleted;
            return isSave ? context.SaveChanges() > 0 : true;
        }

        public bool Exist(Expression<Func<T, bool>> anyLambda)
        {
            return context.Set<T>().Any(anyLambda);
        }

        public T Find(int ID)
        {
            return context.Set<T>().Find(ID);
        }

        public T Find(Expression<Func<T, bool>> whereLambda)
        {
            T _entity = context.Set<T>().FirstOrDefault<T>(whereLambda);
            return _entity;
        }

        public int Save() { return context.SaveChanges(); }
    }
}
